/**
 * @author klv
 */
QS_ExchangeView=function(container,columns,config,callback){
    this.container=container;
    this.callback=callback||{};
    this.columns=columns||[{
        header: "gkey",
        dataIndex: 'gkey',
        hide: true
    }, {
        header: "Market",
        dataIndex: 'Symbol',
        className:'market',
        width: '8%',
        align: 'left'
    },{
        header: "Advance %",
        dataIndex: '909',
        width: '14%',
		className:'advance bold-cell',
        align: 'right',
        dataType: 'float'
    },{
        header: "Decline %",
        dataIndex: '910',
		className:'decline bold-cell',
        width: '13%',
        align: 'right',
        dataType: 'float'
    }, {
        header: "Unchanged %",
        dataIndex: '911',
		className:'unchanged bold-cell',
        width: '16%',
        align: 'right',
        dataType: 'float'
    }, {
        header: "Advanced vol (mil)",
        dataIndex: '912',
        className:'advancedvol',
        width: '11%',
        align: 'right',
        dataType: 'float'
    }, {
        header: "Declined vol (mil)",
        dataIndex: '913',
        className:'declinedvol',
        width: '11%',
        align: 'right',
        dataType: 'float'
    }, {
        header: "Unchanged vol (mil)",
        dataIndex: '914',
        className:'unchangedvol',
        width: '12%',
        align: 'right',
        dataType: 'float'
    },{
        header: "Total volume",
        dataIndex: 'Tol-vol',
        className:'totalvol',
        width: '15%',
        align: 'right',
        dataType: 'float'
    }];
    this.config={
		column:this.columns,
		indexColKey:'gkey',
		lazyLoad: false,
		sortable: true,
		cellResize: false,
		cellRearrange: false,
		alternateRow: false,
		autoWidth:true,
		autoHeight:!config.fixHeight
    };
    if(config){
        $.extend(true,this.config,config);
    }
    this.el=null;
    this.html='<div class="qs-listview"></div>';
    this.grid=null;
    this.contentKey = document.body.textContent ? 'textContent' : 'innerText';
    this.init();
};
QS_ExchangeView.prototype={
    init:function(){
        this.el=$(this.html).appendTo(this.container);
        this._createGrid();
    },
    _createGrid:function(){
        this.grid=new Util.DataGrid(this.el,{},this.config,this.callback);
    },
	changeOutSize:function(w,h){
		this.grid.resize(w,h);
	},
    reBindData:function(data){
        this.grid.reBindData(data);
    },
	addRow:function(data, id, idx){
		this.grid.addRow(data, id, idx);
	},
	existRow:function(rowid){
		 return !$.isEmptyObject(this.grid.DOMMap[rowid]);
	},
    updateData:function(key,aData){
        if(!this.grid.DOMMap[key]){
            return;
        }
        for (var field in aData) {
            gValue = aData[field].value;
            oValue = aData[field].oValue;
            if (typeof gValue != 'undefined' && gValue != null) {
                this.updateDOM(key, field, gValue, oValue);
            }
        }
    },
	forceUpdateData:function(list,gData){
		var key=null;
		for(var i=0,l=list.length;i<l;i++){
			key=list[i];
			var cols=gData[key];
			if (typeof cols != 'undefined') {
				for (var field in cols) {
					this.updateDOM(key, field, cols[field]);
				}
			}
		}
	},
    updateDOM:function(key, field, data, oldData){
        var contentKey=this.contentKey;
		field=field.replace(/D/,"");
        var el = this.grid.DOMMap[key]?this.grid.DOMMap[key][field]:null;
        if(!el){
            return;
        }
        switch (field) {
            case '909':
			    var d = data;
                flashWithDirectional(el,data,oldData,true);
				break;
            case '910':
			    var d = data;
                flashWithDirectional(el,data,oldData,false);
				break;
            case '911':
                var d = data;
                flashWithDirectional(el,data,oldData,d>=0);
                break;
            case '912':
            case '913':
			case '914':
			case 'Tol-vol':
                data = data / 1000000;
                data = data.toFixed(3);
                flash(el,null,null);
                break;
            default:
                break;
        }
        el[contentKey] = data;
    }
};

QS_BaseExchangeActivity={
    selectExchCode:["127","126"],
    securityType: 1,
    exchangeInfo:{
        "126":{
            tradeTicker:"MSTATS_ALL",//this is a composite market ticker
            txt:"USA",
            val:"usa",
            subExchange:[
                {
                    exchCode:"1",
                    tradeTicker:"MSTATS_AMEX_T",
                    txt:"AMEX",
                    val:"AMEX"
                },{
                    exchCode:"14",
                    tradeTicker:"MSTATS_NYSE_T",
                    txt:"NYSE",
                    val:"NYSE"
                },{
                    exchCode:"16",
                    tradeTicker:"MSTATS_ARCA_T",
                    txt:"ARCA",
                    val:"ARCA"
                },{
                    exchCode:"19",
                    tradeTicker:"MSTATS_NASDAQ_T",
                    txt:"NASDAQ",
                    val:"NASDAQ"
                }
            ]
        },
        "127":{
            tradeTicker:"MSTATS_ALL",
            txt:"Canada",
            val:"can",
            subExchange:[
                {
                    exchCode:"127",
                    tradeTicker:"MSTATS_TSX_MJ",
                    txt:"Toronto",
                    val:"tor"
                },{
                    exchCode:"127",
                    tradeTicker:"MSTATS_VEN_MJ",
                    txt:"Venture",
                    val:"ven"
                }
            ]
        },
        "134":{
            tradeTicker:"MSTATS_ALL",//this is a composite market ticker
            txt:"HongKong",
            val:"hk"
        }
    },
    getSubscribeTicker:function(mainexch,subexch){
        this.cacheTickers=[];this.newPullTickers=[];
        var mainExhCode=null,mainExchange=null,subExchange=null;
        for(var i=0,l=this.selectExchCode.length;i<l;i++){
            mainExhCode=this.selectExchCode[i];
            mainExchange = this.exchangeInfo[mainExhCode];
            if(!mainExchange) continue;
            if(mainexch){
                this.newPullTickers.push(mainExhCode+"."+this.securityType+"."+mainExchange.tradeTicker);
                this.cacheTickers.push({
                    gkey:mainExhCode+":"+mainExchange.tradeTicker,
                    paraList:[{
                        sourceType:"D",serviceName:mainExhCode,
                        itemName:this.securityType+push.subSeparator+mainExchange.tradeTicker+push.subSeparator+"-1"
                    }],
                    staticType:this.securityType,isSubscribeLevelII:false});
            }
            if(mainExchange["subExchange"]&&subexch){
                for(var j=0,h=mainExchange["subExchange"].length;j<h;j++){
                    subExchange = mainExchange["subExchange"][j];
                    exchcode = subExchange["exchCode"];
                    this.newPullTickers.push(exchcode+"."+this.securityType+"."+subExchange.tradeTicker);
                    this.cacheTickers.push({
                        gkey:exchcode+":"+subExchange.tradeTicker,
                        paraList:[{
                            sourceType:"D",serviceName:exchcode,
                            itemName:this.securityType+push.subSeparator+subExchange.tradeTicker+push.subSeparator+"-1"
                        }],
                        staticType:this.securityType,isSubscribeLevelII:false});
                    }
            }
        }
    },
	intervalTime:60000,
    tokens: {D909:'Adv%',D910:'Dec%',D911:'Unchg%',D912:'Adv-vol',D913:'Dec-vol',D914:'Unchg-vol',"Tol-vol":"Tol-vol"},
    batchSubscribeMainTickers:function(){
        if(typeof GB_DataManager!='undefined'){
            GB_DataManager.batchSubscribe(this.cacheTickers);
        }
    },
	batchUnsubscribeMainTickers:function(){
        if(typeof GB_DataManager!='undefined'){
            GB_DataManager.batchUnsubscribe(this.cacheTickers,true);
        }
    },
	getTotalVol:function(gdata){
		return (parseFloat((gdata["D912"]||gdata["912"]).value) + parseFloat((gdata["D913"]||gdata["913"]).value) + parseFloat((gdata["D914"]||gdata["914"]).value));
	}
};
var QS_ExchangeActivityManager=function(){
    var activityMap={};
    return {
        register:function(id,obj){
            activityMap[id]=obj;
        },
        unregister:function(id){
            delete activityMap[id];
        },
        updateData:function(gkey,adata){
            for(var id in activityMap){
                activityMap[id].updateData(gkey,adata);
            }
        }
    }
}();
var QS_ExchangeActivity=function(container,config,callback,id){
	this.container=container;
	this.cacheGkeyList=[];//["126:symbol"]
	this.config={
		isNewPull:true,
		quoteURL:'getNewPullData.jsp',
		fixHeight:true,
		title:'Market diary',
        showSub:true,
        showMain:true,
        showTitle:false,
        isAPI:true
	};
	this.staticValue={
		minWidth:900,
		titleHeight:13,
        winTitle:26,
        winPadding:5
	};
    this.id=id||-1;
	this.firstTag=true;
	this.lastHeight=0;
	this.callback=callback||{};
	$.extend(this.config,config);
};
QS_ExchangeActivity.prototype=$.extend({},QS_BaseExchangeActivity,{
	init:function(exchange){
		if (typeof exchange!= 'undefined' && !exchange.selectExchCode&& exchange.selectExchCode.length > 0) {
			this.selectExchCode = exchange.selectExchCode;
		}
        this.getSubscribeTicker(this.config.showMain,this.config.showSub);
        QS_ExchangeActivityManager.register(this.id,this);
		this.el=$('<div class="qs-ui-exchangeactivity">'+(!this.config.showTitle?'':'<div class="qs-listview-hd">'+this.config.title+'</div>')+'<div class="qs-listview-bd"></div></div>').appendTo(this.container);
		if(this.config.width){
			this.el.css({width:this.config.width});
		}
        if(!this.config.isAPI&&!isNaN(this.config.height)){
            this.config.height-=this.staticValue.winTitle;
        }  
		this.dataGridList=new QS_ExchangeView(this.el.find(".qs-listview-bd"),null,this.config,{});
		this._createSymbolData();
		this.foreUpdateData();
		if(this.config.isNewPull){
			this.quoteTickers();
            this.batchSubscribeMainTickersByNewpull();
		}else{
			this.batchSubscribeMainTickers();
		}
		if (this.firstTag) {
			Util.DelayRun('onload.ExchangeActivity', this.loadHandler, 100, this);
		}
		else {
			Util.DelayRun('heightchange.ExchangeActivity', this.heightChangeHandler, 100, this);
		}
	},
	heightChangeHandler:function(){
		 if(this.config.fixHeight&&typeof this.callback.onHeightChange=='function'){
			var height=this.el.height(),width=this.el.width();
			if(this.lastHeight!=height){
				this.callback.onHeightChange({
					component: "ExchangeActivity",
					height: height,
					width : width
				});
				this.lastHeight=height;
			}
		}
	},
	loadHandler:function(){
		if(typeof this.callback.onLoad=='function'){
			var height=this.el.height();
			this.callback.onLoad({
				component:"ExchangeActivity",
				height: height,
				minWidth : this.staticValue.minWidth
            });
            this.firstTag = false;
        }
	},
	_quoteNewPullTickers:function(){
		var separator=".";
		if (typeof this.cachepulldata == 'undefined') {
            var para = {
                tickers: this.newPullTickers.join(",")
            };
            if (this.tokens && this.tokens != '') {
                var tockenlist = [];
                for (var token in this.tokens) {
                    if (token != 'Tol-vol') {
                        tockenlist.push(token);
                    }
                }
                para["tokens"] = tockenlist.join(',');
            }
            this.cachepulldata=para;
        }
        return this.cachepulldata;
	},
	batchSubscribeMainTickersByNewpull:function(){
        var self=this;
        if (this.mainIntervalObj == null) {
            this.mainIntervalObj = setInterval(function(){
                self.quoteTickers();
            }, this.intervalTime);//GB_DataManager.dataObj.rate[this.config.data]*1000);
        }
    },
	batchUnSubscribeMainTickersBypull:function(){
        if(this.mainIntervalObj!=null){
            clearInterval(this.mainIntervalObj);
            this.mainIntervalObj=null;
        }
    },
	quoteTickers:function(){
        if(!$.isEmptyObject(typeof gNewPull!='undefined')) return;
		var self=this;
		$.getJSON(PULL_Path+this.config.quoteURL+"?cb=?",this._quoteNewPullTickers(), function(o){
			if(typeof o=='undefined')return false;
			if (o.errorcode) {
				return;
			}else{
				self._newPullUpdate(o);
			}
        });
	},
	_newPullUpdate:function(o){
		var self=this;
        var items=o.items
        if(items&&items.length>0){
            var exch=null,gkey=null,fields=null,tempAL=null,aL=null;
			if(typeof gNewPull=='undefined'){
				gNewPull={};
			}
            for(i=0,l=items.length;i<l;i++){
                exch=items[i].service;
                tempAL=items[i].symbol.split("|");
                if(tempAL.length==1){
                    tempAL=items[i].symbol.split("_");
                }
                if(tempAL.length==3){
                    aL = tempAL;
                }else if(tempAL.length>3){// handle pull return 
                    aL=[];
                    aL[0]=tempAL[0];
                    var temp=[],tempALLength =tempAL.length;
                    for(var ti=1;ti<tempALLength-1;ti++){
                        temp.push(tempAL[ti]);
                    }
                    aL[1]=temp.join("_");//merge ticker
                    aL[2]=tempAL[tempALLength-1];
                }
                gkey=exch+":"+aL[1];
                if(!gNewPull[gkey]){
                    gNewPull[gkey]={};
                }

                fields=items[i].fields;
				var needUpdateField={};
                var fieldName,fieldValue,token,gridData;
                if(fields.length>0){
                    for(var j=0,jl=fields.length;j<jl;j++){
                        gridData=[];
                        fieldName=fields[j].name;
                        fieldValue=fields[j].value;
						if(this.cachepulldata["tokens"].indexOf(fieldName)!=-1){
                            var token=fieldName;
                            var oldFieldValue=gNewPull[gkey][fieldName];
                            if(oldFieldValue==fieldValue){
                                continue;
                            }
                            gNewPull[gkey][fieldName]=fieldValue;
							needUpdateField[fieldName]={
			                    value:fieldValue,
			                    oValue:oldFieldValue,
			                    dataType:'s'
			                };
                        }else{
                            continue;
                        }
                    }
					QS_ExchangeActivityManager.updateData(gkey,needUpdateField);
                }
            }
        }
	},
	updateData: function(gkey, aData){
        if($.inArray(gkey,this.cacheGkeyList)>-1){
            this.batchReBindGrid(gkey,aData);
        }
    },
	foreUpdateData:function(){
		this.dataGridList.forceUpdateData(this.cacheGkeyList,this.config.isNewPull?(typeof gNewPull!='undefined'?gNewPull:{}):gData);
	},
	_createSymbolData:function(){
		var gridData=[],gkey=null,mainExhCode=null,mainExchange=null,subExchange=null;
        for(var i=0,l=this.selectExchCode.length;i<l;i++){
            mainExhCode=this.selectExchCode[i];
            mainExchange = this.exchangeInfo[mainExhCode];
            if(!mainExchange) continue;
            if(this.config.showMain){
                gkey = mainExhCode+":"+mainExchange.tradeTicker;
                this.cacheGkeyList.push(gkey);
                gridData.push({
                    gkey: gkey,
                    Symbol: mainExchange.txt
                });
            }
            if(mainExchange["subExchange"]&&this.config.showSub){
                for(var j=0,h=mainExchange["subExchange"].length;j<h;j++){
                    subExchange = mainExchange["subExchange"][j];
                    exchcode = subExchange["exchCode"];
                    gkey =exchcode+":"+subExchange.tradeTicker;
                    this.cacheGkeyList.push(gkey);
                    gridData.push({
                        gkey: gkey,
                        Symbol: subExchange.txt
                    });
                }
            }
        }
		this.dataGridList.reBindData(gridData);
	},
	batchReBindGrid:function(gkey,aData){
		var cachdata=this.config.isNewPull?gNewPull:gData;
		if (aData["D912"]||aData["912"]|| aData["D913"]||aData["913"]|| aData["D914"]||aData["914"]) {
			aData["Tol-vol"]={};
			var total=this.getTotalVol(aData);
			cachdata[gkey]["Tol-vol"]=aData["Tol-vol"].value = total;
		}
		if(this.dataGridList.existRow(gkey)){
			this.dataGridList.updateData(gkey,aData);
		}
    },
	saveConfig:function(){
        return {
        };      
    },
	clear:function(){
        QS_ExchangeActivityManager.unregister(this.id);
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },  
	clearData:function(){
		this.batchUnsubscribeMainTickers();
	},
	changeOutSize:function(w,h){
        if(!this.config.isAPI){
    		w=w||this.container.parent().width();
            h=h||this.container.parent().height();
            h-=this.staticValue.winPadding;
        }else{
            w=this.config.width||w||this.container.width();
            h=this.config.height||h||this.container.height();
            this.el.css({width:"auto"});
        }
		if(this.config.showTitle){
			h=h-this.staticValue.titleHeight;
		}
		if(this.config.fixHeight){
			this.dataGridList.changeOutSize(w,h);
		}else{
			this.dataGridList.changeOutSize(w,'auto');
		}
		if (this.firstTag) {
			Util.DelayRun('onload.ExchangeActivity', this.loadHandler, 100, this);
		}
		else {
			Util.DelayRun('heightchange.ExchangeActivity', this.heightChangeHandler, 100, this);
		}
	}
});
